<template>
	<div>
		<div class="toolbar mt-2">
			<a-form ref="searchRef" :model="searchState" :label-col="{style: { width: '80px' }}" @finish="initData">
				<a-row :gutter="20">
					<a-col :md="12" :lg="8" :xl="8">
						<a-form-item label="标题" class="mb-0">
							<a-input v-model:value="searchState['title']" placeholder="请输入" allow-clear></a-input>
						</a-form-item>
					</a-col>
					<a-col :md="12" :lg="8" :xl="8">
						<a-space>
							<a-button type="primary" html-type="submit">
								<search-outlined />搜索
							</a-button>

							<a-button type="primary" @click="addModule">
								<plus-outlined />添加
							</a-button>
							<a-button danger :disabled="!selectedRowKeys.length" @click="deleteModule">
								<delete-outlined />删除
							</a-button>
						</a-space>
					</a-col>
				</a-row>
			</a-form>
		</div>

		<div class="container mt-2">
			<!--v-if="moduleSource.length"适配:default-expand-all-rows="true"-->
			<a-table v-if="moduleSource.length" row-key="id" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: changeSelectedRowKeys }" :default-expand-all-rows="false" :scroll="tableScroll" :data-source="moduleSource" :pagination="false" :loading="loading" :columns="columns">
				<template #bodyCell="{ column, record }">
					<template v-if="column.key === 'operation'">
						<a-space>
							<a-button v-if="record.type === 1" type="link" @click="addModule(record.id)">
								<plus-outlined />添加
							</a-button>

							<a-button type="link" @click="editModule(record)">
								<edit-outlined />修改
							</a-button>
							<a-button type="link" style="color:#ff7875" @click="deleteModule(record.id)">
								<delete-outlined />删除
							</a-button>
						</a-space>
					</template>
				</template>
			</a-table>

			<a-empty v-else></a-empty>
		</div>

		<a-modal v-model:visible="visible" title="模块信息" :width="500">
			<a-form ref="formRef" :model="formState" :rules="formRules" layout="horizontal" v-bind="{labelCol: { style: { width: '80px' } }}">
				<a-form-item label="类型" name="type">
					<a-radio-group v-model:value="formState.type">
						<a-radio :value="1">菜单</a-radio>
						<a-radio :value="2">按钮</a-radio>
					</a-radio-group>
				</a-form-item>
				<a-form-item label="标题" name="title">
					<a-input v-model:value="formState.title" />
				</a-form-item>
				<a-form-item label="上级菜单" name="parent_id">
					<a-tree-select v-model:value="formState.parent_id" placeholder="选择上级菜单" :allow-clear="true" :show-search="true" :tree-checkable="false" :dropdown-style="{}" tree-default-expand-all :tree-data="moduleTree" :field-names="{children: 'children', label: 'title', value: 'id'}" tree-node-filter-prop="title"></a-tree-select>
				</a-form-item>

				<template v-if="formState.type === 1">
					<a-form-item label="名称" name="name">
						<a-input v-model:value="formState.name" />
					</a-form-item>
					<a-form-item label="路径" name="path">
						<a-input v-model:value="formState.path" />
					</a-form-item>
					<a-form-item label="组件" name="component">
						<a-input v-model:value="formState.component" />
					</a-form-item>
					<a-form-item label="图标" name="icon">
						<a-input v-model:value="formState.icon" />
					</a-form-item>
					<a-form-item label="排序" name="sort">
						<a-input v-model:value="formState.sort" />
					</a-form-item>
					<a-form-item label="是否可见" name="status">
						<a-radio-group v-model:value="formState.is_visible">
							<a-radio :value="1">显示</a-radio>
							<a-radio :value="0">隐藏</a-radio>
						</a-radio-group>
					</a-form-item>
					<a-form-item label="状态" name="status">
						<a-radio-group v-model:value="formState.status">
							<a-radio :value="1">开启</a-radio>
							<a-radio :value="0">关闭</a-radio>
						</a-radio-group>
					</a-form-item>
				</template>
			</a-form>

			<template #footer>
				<a-space>
					<a-button @click="visible=false">关闭</a-button>
					<a-button type="primary" @click="saveModule">提交</a-button>
				</a-space>
			</template>
		</a-modal>
	</div>
</template>
<script setup lang="jsx">
import { SearchOutlined, EditOutlined, DeleteOutlined, PlusOutlined } from "@ant-design/icons-vue";

import { reactive, ref, computed, getCurrentInstance } from "vue";

const { proxy } = getCurrentInstance();

import { post, listToTree } from "../utils";

const searchRef = ref();
const searchState = reactive({});

const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 210 }));

const columns = [
	{
		title: "ID",
		dataIndex: "id",
		key: "id",
		width: 140,
		align: 'left',
		fixed: "left"
	},
	{
		title: "排序",
		dataIndex: "sort",
		sorter: false,
		fixed: "left",
		width: 60
	},
	{
		title: "标题",
		dataIndex: "title",
		sorter: false,
		fixed: "left",
		width: 200,
		customRender: ({ text, record, index, column }) => {
			return record.title;
		}
	},
	{
		title: "名称",
		dataIndex: "name",
		sorter: false,
		width: 200
	},
	{
		title: "路径",
		dataIndex: "path",
		sorter: false,
		width: 160
	},
	{
		title: "类型",
		dataIndex: "type",
		sorter: false,
		width: 120,
		customRender: ({ text, record, index, column }) => {
			return text === 1 ? <a-tag color="green">菜单</a-tag> : <a-tag color="blue">按钮</a-tag>;
		}
	},
	{
		title: "是否可见",
		dataIndex: "is_visible",
		sorter: false,
		width: 120,
		customRender: ({ text, record, index, column }) => {
			return text === 1 ? <a-tag color="green">是</a-tag> : <a-tag>否</a-tag>;
		}
	},
	{
		title: "状态",
		dataIndex: "status",
		sorter: false,
		width: 120,
		customRender: ({ text, record, index, column }) => {
			return text === 1 ? <a-tag color="green">开启</a-tag> : <a-tag>关闭</a-tag>;
		}
	},
	{},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 200,
		align: "center"
	}
];

const selectedRowKeys = ref([]);

const changeSelectedRowKeys = keys => {
	selectedRowKeys.value = keys;
};

const loading = ref(true);
const moduleSource = ref([]);

const initData = (pag, filters, sorter) => {
	post("module", { ...searchState }).then((data) => {
		moduleSource.value = listToTree(data, 0);
		loading.value = false;
	})
};
initData();

const deleteModule = (id) => {
	if (typeof id === "object") id = selectedRowKeys.value.join(",");
	if (!id) {
		proxy.$message.error("请选择需要删除的模块");
		return;
	}
	
	proxy.$confirm({
		title: "确认提示",
		content: `确定要删除${typeof id === "number" ? "当前" : "选中"}的模块吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("module/delete", { id }).then(() => {
				proxy.$message.success("模块删除成功");
				
				//最后一条记录删除后需要返回上一页
				initData()
			});
		}
	});
}

const visible = ref(false);
const formState = ref({});
const formRef = ref();

const formRules = computed(() => {
	const { type = 1, parent_id } = formState.value;
	return {
		type: [{ required: true, message: "请选择类型", trigger: "blur" }],
		title: [{ required: true, message: "请输入标题", trigger: "blur" }],

		name: [{ required: type === 1 && parent_id > 0 ? true : false, message: "请输入名称", trigger: "blur" }],

		path: [{ required: type === 1 ? true : false, message: "请输入路径", trigger: "blur" }]
	}
});

const moduleTree = ref([]);

/*
watch(() => formState.value.id, async (value) => {
	//新增
	if (!value) {
		moduleTree.value = await post('module/tree', { type: 1 });
	} else {
		moduleTree.value = await post('module/tree', { type: 1, exclude_id: value });
	}
});
*/

const addModule = async (parent_id = 0) => {
	moduleTree.value = await post('module/tree', { type: 1 });

	formRef.value?.clearValidate();
	visible.value = true;
	
	if (typeof parent_id === 'object') parent_id = null;
	formState.value = { id: null, type: 1, parent_id, is_visible: 1, status: 1 };
}

const editModule = async (record) => {
	moduleTree.value = await post('module/tree', { type: 1, exclude_id: record.id });

	formRef.value?.clearValidate();
	visible.value = true;
	
	const data = { ...record };
	//fix 0
	if (!data.parent_id) data.parent_id = null;

	formState.value = data;
}

const saveModule = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();

			const params = { ...formState.value };

			post('module/save', params).then(() => {
				proxy.$message.success('模块信息提交成功', 1);
				visible.value = false;
				
				initData();
			}).catch((err) => {
				proxy.$message.error(err);
			});
		})
		.catch(err => {
			
		});
}
</script>

<style scoped lang="scss">
.toolbar {
	padding: 12px;
	background: #fff;

	.ant-form {
		position: relative;
		margin-bottom: -24px;
	}
}
</style>
